package com.huiquan.icd.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.framework.utils.ExcelUtil;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.RespHeaderUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.dao.IcdCodeDao;
import com.huiquan.icd.dao.IcdDiseaseCategoryDao;
import com.huiquan.icd.dao.IcdDiseaseDao;
import com.huiquan.icd.dao.IcdDiseaseNameRecordDao;
import com.huiquan.icd.domain.IcdCode;
import com.huiquan.icd.domain.IcdCodeDto;
import com.huiquan.icd.domain.IcdDisease;
import com.huiquan.icd.domain.IcdDiseaseCategory;
import com.huiquan.icd.domain.IcdDiseaseNameRecord;

@Service
public class IcdCodeService extends BaseService {

	@Autowired
	private IcdCodeDao icdCodeDao;
	@Autowired
	private IcdDiseaseDao icdDiseaseDao;
	@Autowired
	private IcdDiseaseCategoryDao icdDiseaseCategoryDao;
	@Autowired
	private IcdDiseaseNameRecordDao icdDiseaseNameRecordDao;
	@Autowired
	private IcdDiseaseHospitalService icdDiseaseHospitalService;
	
	public ModelAndView list(Integer start, String codeSearch, String nameSearch, String categorySearch,
			String exactSearchFlag, String modifyFlag,String countPerPageStr) {
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		if (codeSearch != null && !codeSearch.isEmpty()) {
			param.put("codeSearch", exactFlag ? codeSearch : "%" + codeSearch + "%");
		}
		if (nameSearch != null && !nameSearch.isEmpty()) {
			param.put("nameSearch", exactFlag ? nameSearch : "%" + nameSearch + "%");
		}
		if (categorySearch != null && !categorySearch.isEmpty()) {
			param.put("categorySearch", exactFlag ? categorySearch : "%" + categorySearch + "%");
		}
		if (modifyFlag != null && "1".equals(modifyFlag)) {
			param.put("modifyFlag", modifyFlag);
		}
		int totalSize = icdCodeDao.retrieveSize(param);

		Map<String, Integer> pageNo ;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start+"", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start+"");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<IcdCodeDto> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = icdCodeDao.retrieveDtoList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("codeSearch", "编码");
		showSearch.put("nameSearch", "疾病名");
		showSearch.put("categorySearch", "一级");

		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("codeSearch", codeSearch);
		searchMap.put("nameSearch", nameSearch);
		searchMap.put("categorySearch", categorySearch);
		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("exactSearchFlag", exactSearchFlag);
		map.put("modifyFlag", modifyFlag);
		return new ModelAndView("icd/index", map);
	}

	public ModelAndView preEdit(String codeSearch, String nameSearch, String categorySearch, Integer start, String id,
			User user, String exactSearchFlag, String modifyFlag) {
		// 如果id不为空则表示是修改，否则为新增
		Map<String, Object> map = new HashMap<>();
		if (id != null && !id.isEmpty()) {
			IcdCodeDto icdCode = icdCodeDao.retrieveDtoById(Long.parseLong(id));
			map.put("code", icdCode.getCode());
			map.put("name", icdCode.getName());
			map.put("disable", icdCode.getDisable());
			map.put("category", icdCode.getCategory());
			map.put("pName", icdCode.getpName());
			map.put("gpName", icdCode.getGpName());
			map.put("cnt", icdCode.getCnt());
			map.put("urgentFlag", icdCode.getUrgentFlag());
		}

		map.put("id", id);
		map.put("start", start);
		map.put("codeSearch", codeSearch);
		map.put("nameSearch", nameSearch);
		map.put("categorySearch", categorySearch);
		map.put("exactSearchFlag", exactSearchFlag);
		map.put("modifyFlag", modifyFlag);

		return new ModelAndView("icd/code_edit", map);
	}

	public ReturnData edit(String id, String code, String name, Integer disable, String category, User user,
			String changeFlag) throws Exception {

		// 校验一级是否是有效且展现的疾病名称
		IcdDisease categoryDisease = icdDiseaseDao.retrieveObject(category, BaseContants.DISABLE_VALID,
				BaseContants.FLAG_NO);
		Long categoryDiseaseId = 0l;
		if (!category.equals(name) && categoryDisease == null) {
			return ReturnUtil.fail(ReturnCode.ICD_CATEGORY_NOT_EXISTS);
		}
		if (categoryDisease != null) {
			categoryDiseaseId = categoryDisease.getId();
		}

		// 分解disable字段
		int diseaseDisable = disable == 2 ? 1 : 0; // disable为2时才无效
		int diseaseHiddenFlag = disable == 0 ? 0 : 1; // disable为0是才展现

		// 构建编码实体
		IcdCode icdCode = new IcdCode();
		icdCode.setCode(code);
		icdCode.setModifierId(user.getUserId());

		// id存在为修改，不存在为新增
		if (id != null && !id.isEmpty()) {
			icdCode.setId(Long.parseLong(id));

			// 更新编码中的信息
			IcdDisease icdDisease = getDiseaseByName(name, user, diseaseDisable, diseaseHiddenFlag, category,
					categoryDiseaseId); // 根据提交的名称获取疾病
			icdCode.setDiseaseId(icdDisease.getId());

			// 维护疾病
			IcdCodeDto icdCodeDto = icdCodeDao.retrieveDtoById(Long.parseLong(id)); // 修改前的code
			IcdDisease oldIcdDisease = icdDiseaseDao.retrieveObjectById(icdCodeDto.getDiseaseId()); // 修改前的disease
			String oldName = oldIcdDisease.getName();
			if (!name.equals(oldName)) { // 修改前后的疾病名称不同则需维护
				if ("1".equals(changeFlag)) {
					// 如果是批量修改疾病名，则根据diseaseId进行替换
					icdCodeDao.changeDiseaseId(icdCodeDto.getDiseaseId(), icdDisease.getId());
					// 维护修改疾病名称记录表
					nameUpdateRecord(oldName, name, user.getUserId());
				}
			}
			
			icdCodeDao.update(icdCode);
			
			// 修改前疾病无编码使用则失效，对应一级替换
			updateDiseaseInvalidByUsed(oldIcdDisease, icdDisease, user);
			
		} else {
			// 判断编码是否已存在
			int existCode = icdCodeDao.retrieveExistedSizeByCode(code);
			if (existCode > 0) {
				LOGGER.error("Code existed in database when it insert; code = " + code);
				return ReturnUtil.fail(ReturnCode.ICD_CODE_EXISTED);
			}

			// 维护编码中的疾病ID
			IcdDisease icdDisease = getDiseaseByName(name, user, diseaseDisable, diseaseHiddenFlag, category,
					categoryDiseaseId); // 根据提交的名称获取疾病
			icdCode.setDiseaseId(icdDisease.getId());
			Long newId = icdCodeDao.insert(icdCode);
			icdCode.setId(newId);

			// 设置pid和gpid
			setPid(icdCode);
			
			
			
			// 新增时编码如果是类目或亚目，则维护历史数据
			setHistoryDataPid(newId, code);
			
		}
		
		
		return ReturnUtil.success();
	}

	private Long getCategoryIdByName(String category, Long categoryDiseaseId, User user) {
		IcdDiseaseCategory icdDiseaseCategory = icdDiseaseCategoryDao.retrieveObjectByName(category);
		if (icdDiseaseCategory == null) {
			icdDiseaseCategory = new IcdDiseaseCategory();
			icdDiseaseCategory.setName(category);
			icdDiseaseCategory.setDiseaseId(categoryDiseaseId);
			icdDiseaseCategory.setCreatorId(user.getUserId());
			icdDiseaseCategory.setCreatorName(user.getRealName());
			icdDiseaseCategory.setModifierId(user.getUserId());
			icdDiseaseCategory.setModifierName(user.getRealName());
			icdDiseaseCategoryDao.insert(icdDiseaseCategory);
		}
		return icdDiseaseCategory.getId();
	}

	private IcdDisease getDiseaseByName(String name, User user, int diseaseDisable, int diseaseHiddenFlag,
			String category, Long cdId) {
		// 根据名称获取疾病
		IcdDisease icdDisease = icdDiseaseDao.retrieveObject(name, null, null);
		if (icdDisease == null) {
			// 如果疾病不存在，则新增一个疾病
			icdDisease = new IcdDisease();
			icdDisease.setName(name);
			icdDisease.setDisable(diseaseDisable+"");
			icdDisease.setHiddenFlag(diseaseHiddenFlag);
			icdDisease.setCategoryId(0l);
			icdDisease.setModifierId(user.getUserId());
			icdDisease.setDisable(BaseContants.DISABLE_VALID);
			icdDiseaseDao.insert(icdDisease);

			// 维护修改疾病名称记录表
			nameUpdateRecord("", name, user.getUserId());
		} else {
			icdDisease.setDisable(diseaseDisable+"");
			icdDisease.setHiddenFlag(diseaseHiddenFlag);
		}
		// 疾病维护一级
		Long categoryDiseaseId = category.equals(name) ? icdDisease.getId() : cdId;
		icdDisease.setCategoryId(getCategoryIdByName(category, categoryDiseaseId, user));
		icdDiseaseDao.update(icdDisease);

		// 将该疾病名对应的曾用名记录设置为已失效
		icdDiseaseNameRecordDao.disableFormerName(name);

		return icdDisease;
	}

	/**
	 * 修改前疾病无编码使用则失效，对应一级替换
	 * 
	 * @param diseaseId
	 * @param name
	 * @param long1
	 * @param long2
	 */
	private void updateDiseaseInvalidByUsed(IcdDisease oldIcdDisease, IcdDisease newIcdDisease, User user) {
		int otherCodeSize = getCodeSizeByDiseaseId(oldIcdDisease.getId());
		if (otherCodeSize == 0) {
			// 将疾病失效
			icdDiseaseDao.disable(oldIcdDisease.getId(), Integer.parseInt(BaseContants.DISABLE_INVALID));
			// 对应一级替换
			IcdDiseaseCategory newCategory = icdDiseaseCategoryDao.retrieveObjectByName(newIcdDisease.getName());
			if (newCategory == null) {
				// 创建新的一级
				newCategory = new IcdDiseaseCategory();
				newCategory.setName(newIcdDisease.getName());
				newCategory.setDiseaseId(newIcdDisease.getId());
				newCategory.setCreatorId(user.getUserId());
				newCategory.setCreatorName(user.getRealName());
				newCategory.setModifierId(user.getUserId());
				newCategory.setModifierName(user.getRealName());
				icdDiseaseCategoryDao.insert(newCategory);
			}

			// 替换一级
			IcdDiseaseCategory oldCategory = icdDiseaseCategoryDao.retrieveObjectByName(oldIcdDisease.getName());
			if (oldCategory != null) {
				icdDiseaseDao.updateCategory(oldCategory.getId(), newCategory.getId());
			}
		}
	}

	/**
	 * 根据编码和id维护历史数据中的类目和亚目
	 * 
	 * @param id
	 * @param code
	 */
	private void setHistoryDataPid(Long id, String code) {
		// 如果编码长度是三，则为类目编码
		if (code.length() == 3) {
			icdCodeDao.batchUpdatePid(id, code, 1);
		}

		// 如果编码长度是五，且第四位为"."，则为亚目编码
		if (code.length() == 5 && code.indexOf(".") == 3) {
			icdCodeDao.batchUpdatePid(id, code, 2);
		}
	}

	/**
	 * 修改或新增疾病名称时，维护记录
	 * 
	 * @param oldName
	 * @param name
	 * @param l
	 */
	private void nameUpdateRecord(String oldName, String name, long uid) {
		if (!oldName.equals(name)) {
			IcdDiseaseNameRecord record = new IcdDiseaseNameRecord();
			record.setName(name);
			record.setFormerName(oldName);
			record.setModifierId(uid);
			record.setDisable(IcdDiseaseNameRecord.DISABLE_VALID);

			icdDiseaseNameRecordDao.insert(record);
		}
	}

	/**
	 * 新增的编码需要设置pid和gpid
	 * 
	 * @param icdCode
	 */
	private void setPid(IcdCode icdCode) {
		Long gpId = 0l, pId = 0l;
		String code = icdCode.getCode();

		// 设置编码的类目(长度为3类目就是它自己)
		if (code.length() != 3) {
			IcdCodeDto gpCode = getGpcode(code);
			if (gpCode != null) {
				gpId = gpCode.getId();
			}
		} else {
			gpId = icdCode.getId();
		}

		// 设置编码的亚目(长度为5如果有亚目就是它自己)
		if (code.length() != 5) {
			IcdCodeDto pCode = getPcode(code);
			if (pCode != null) {
				pId = pCode.getId();
			}
		} else if (code.indexOf(".") == 3) {
			pId = icdCode.getId();
		}

		icdCode.setGpId(gpId);
		icdCode.setPId(pId);
		icdCodeDao.updatePid(icdCode);
	}

	private int getCodeSizeByDiseaseId(Long diseaseId) {
		Map<String, Object> param = new HashMap<>();
		param.put("diseaseId", diseaseId);
		param.put("modifyFlag", "1");
		return icdCodeDao.retrieveSize(param);
	}

	public ReturnData codeImport(MultipartFile file, User user) throws Exception {

		InputStream inputStream = null;
		Workbook workbook = null;

		try {
			// 获取文件流，解析文件
			inputStream = file.getInputStream();

			workbook = new XSSFWorkbook(inputStream);
			Sheet sheet = workbook.getSheetAt(0);

			// 初始化临时表数据
			Map<String, List<String>> datas = initialTempData(sheet);

			// 校验导入的数据
			ReturnData returnData = new ReturnData(ReturnCode.EXCEPTION, null);
			if (!checkData(returnData, datas)) {
				workbook.close();
				inputStream.close();
				return returnData;
			}

			// 数据维护
			persistData(user);

		} catch (Exception e) {
			throw e;
		} finally {
			workbook.close();
			inputStream.close();
		}
		return ReturnUtil.success();
	}

	private void persistData(User user) {
		// 数据维护，1、新增曾用名；2、新增疾病；3、新增code；4、维护疾病的一级和disable；5、维护code的所有字段
		icdCodeDao.persistImportData(user.getUserId(), user.getRealName());
		icdDiseaseHospitalService.initHospitalDiseaseStdDisable();	
	}

	/**
	 * 校验导入的数据
	 * 
	 * @param returnData
	 * @param datas
	 * @return
	 */
	private boolean checkData(ReturnData returnData, Map<String, List<String>> datas) {

		StringBuffer errMsg = new StringBuffer();

		// 有效的疾病必须有一级
		getCategoryNullError(errMsg);

		// 疾病名不能为曾用名
		getFormerNameByCodeImportTemp(errMsg);

		// code不能重复
		getRepeatingCodeInCodeImportTemp(errMsg);

		// 一级必须是已维护的疾病名
		getErrorCategory(errMsg, datas);

		// 一个疾病名不能修改为两个疾病名
		getUpdateNameError(errMsg);

		// code不能被删除
		getDeleteCode(errMsg);

		// 一个疾病只能有一个一级
		getNameAndCategoryMatchingError(errMsg);

		// 一个疾病只能有一个紧急状态
		getNameAndUrgentFlagMatchingError(errMsg);

		if (errMsg.length() > 0) {
			errMsg.insert(0, "导入失败\n");
			Map<String, Object> data = new HashMap<>();
			data.put("errMsg", errMsg.toString());
			returnData.setReturnCode(ReturnCode.IMPORT_ERROR);
			returnData.setData(data);
			return false;
		}
		return true;
	}

	private void getCategoryNullError(StringBuffer errMsg) {
		List<String> categoryNullError = icdCodeDao.getCategoryNullError();
		getErrMsgByCollection(categoryNullError, errMsg, "以下疾病需要添加一级：");
	}

	/**
	 * 一个疾病只能有一个紧急状态
	 * 
	 * @param errMsg
	 */
	private void getNameAndUrgentFlagMatchingError(StringBuffer errMsg) {
		List<String> matchingError = icdCodeDao.getNameAndUrgentFlagMatchingError();
		getErrMsgByCollection(matchingError, errMsg, "以下疾病无法确定是否紧急：");
	}

	/**
	 * 一个疾病只能有一个一级
	 * 
	 * @param errMsg
	 */
	private void getNameAndCategoryMatchingError(StringBuffer errMsg) {
		List<String> matchingError = icdCodeDao.getImportNameAndCategoryMatchingError();
		getErrMsgByCollection(matchingError, errMsg, "以下疾病有不止一个一级：");
	}

	/**
	 * code不能被删除
	 * 
	 * @param errMsg
	 */
	private void getDeleteCode(StringBuffer errMsg) {
		List<String> deleteCode = icdCodeDao.getImportDeleteCode();
		getErrMsgByCollection(deleteCode, errMsg, "以下编码被删除：");
	}

	/**
	 * 一个疾病名不能修改为两个疾病名
	 * 
	 * @param errMsg
	 */
	private void getUpdateNameError(StringBuffer errMsg) {
		List<String> updateNameError = icdCodeDao.getImportUpdateNameError();
		getErrMsgByCollection(updateNameError, errMsg, "以下疾病名修改为两个疾病名：");
	}

	/**
	 * 一级必须是已维护的疾病名
	 * 
	 * @param errMsg
	 * @param datas
	 */
	private void getErrorCategory(StringBuffer errMsg, Map<String, List<String>> datas) {
		Set<String> validAndDisplayNames = new HashSet<>(datas.get("validAndDisplayNames"));
		Set<String> categorySet = new HashSet<>(datas.get("category"));
		categorySet.removeAll(validAndDisplayNames);
		categorySet.remove("");
		categorySet.remove(null);
		getErrMsgByCollection(categorySet, errMsg, "以下一级不是有效的疾病名：");
	}

	/**
	 * 根据导入的数据获取重复的编码
	 * 
	 * @param errMsg
	 */
	private void getRepeatingCodeInCodeImportTemp(StringBuffer errMsg) {
		List<String> repeatingCodes = icdCodeDao.getRepeatingCodeInCodeImportTemp();
		getErrMsgByCollection(repeatingCodes, errMsg, "以下编码有重复：");
	}

	/**
	 * 根据导入的数据获取疾病名中是否有曾用名
	 * 
	 * @param errMsg
	 */
	private void getFormerNameByCodeImportTemp(StringBuffer errMsg) {
		List<String> formerNames = icdDiseaseNameRecordDao.getFormerNameByCodeImportTemp();
		getErrMsgByCollection(formerNames, errMsg, "以下疾病名为曾用名：");
	}

	/**
	 * 根据集合内容拼凑错误信息
	 * 
	 * @param collection
	 * @param errMsg
	 * @param title
	 */
	private void getErrMsgByCollection(Collection<String> collection, StringBuffer errMsg, String title) {
		if (collection != null && !collection.isEmpty()) {
			errMsg.append(title);
			for (String item : collection) {
				errMsg.append(item);
				errMsg.append("；");
			}
			errMsg.append("\n");
		}
	}

	/**
	 * 初始化临时表数据
	 * 
	 * @param sheet
	 */
	private Map<String, List<String>> initialTempData(Sheet sheet) {

		icdCodeDao.deleteImportTemp();

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		List<String> codes = new ArrayList<>();
		List<String> validAndDisplayNames = new ArrayList<>();
		List<String> categorys = new ArrayList<>();

		ExcelUtil.deleteTitleRow(sheet);

		for (Row row : sheet) {
			int disable = (int) row.getCell(3).getNumericCellValue();
			map = new HashMap<String, Object>();
			map.put("code", row.getCell(0).getStringCellValue());
			codes.add(row.getCell(0).getStringCellValue());
			map.put("name", row.getCell(1).getStringCellValue());
			if (disable == IcdCode.DISABLE_VALID_DISPLAY) {
				validAndDisplayNames.add(row.getCell(1).getStringCellValue());
			}
			map.put("urgentFlag", row.getCell(2).getNumericCellValue());
			map.put("disable", disable == 2 ? 1 : 0);
			map.put("hiddenFlag", disable == 0 ? 0 : 1);
			if (row.getCell(3).getNumericCellValue() != IcdCode.DISABLE_INVALID_HIDDEN && row.getCell(4) != null) {
				map.put("category", row.getCell(4).getStringCellValue());
				categorys.add(row.getCell(4).getStringCellValue());
			} else {
				map.put("category", "");
			}
			list.add(map);

			if (list.size() == 2000) {
				icdCodeDao.insertImportTemp(list);

				list.clear();
			}
		}
		if (list != null && list.size() > 0) {
			icdCodeDao.insertImportTemp(list);
		}

		// 记录数据后续使用
		Map<String, List<String>> datas = new HashMap<>();
		datas.put("code", codes);
		datas.put("validAndDisplayNames", validAndDisplayNames);
		datas.put("category", categorys);

		return datas;
	}

	public void codeExport(HttpServletResponse resp) throws Exception {
		// 获取已校验code列表
		List<IcdCodeDto> codeList = icdCodeDao.retrieveCheckedList();
		LOGGER.info("codeExport get list success!size=" + codeList.size());

		// 设置respons的头信息
		RespHeaderUtil.setXlsxResp(resp, "icd10_code");

		// 创建文档
		XSSFWorkbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("code"); // 创建Sheet

		// 写入标题行
		ExcelUtil.setTitleToFirstRow(workbook,
				new String[] { "icd10编码", "疾病名", "是否紧急", "是否有效", "一级", "类目", "亚目", "频数" });

		// 循环写入数据
		IcdCodeDto code = null;
		Row row = null;
		for (int i = 0; i < codeList.size(); i++) {
			code = codeList.get(i);

			row = sheet.createRow(i + 1);

			List<String> cellValues = new ArrayList<>();
			cellValues.add(code.getCode());
			cellValues.add(code.getName());
			cellValues.add(code.getUrgentFlag().toString());
			cellValues.add(code.getDisable().toString());
			cellValues.add(code.getCategory());
			cellValues.add(code.getGpName());
			cellValues.add(code.getpName());
			cellValues.add(code.getCnt().toString());

			addCell(row, cellValues);
		}
		LOGGER.info("codeExport create excel success!");

		OutputStream os = resp.getOutputStream();
		workbook.write(os);
		workbook.close();

		os.close();
	}

	private void addCell(Row row, List<String> cellValues) {
		if (cellValues.size() > 0) {
			Cell cell = null;
			for (int i = 0; i < cellValues.size(); i++) {
				String cellValue = cellValues.get(i);
				if (i == 2 || i == 3 || i == 7) {
					cell = row.createCell(i, Cell.CELL_TYPE_NUMERIC);
					cell.setCellValue(Integer.parseInt(cellValue));
				} else {
					cell = row.createCell(i);
					cell.setCellValue(cellValue);
				}
			}
		}
	}

	/**
	 * 根据编码获取类目和亚目
	 * 
	 * @param code
	 * @return
	 */
	public ReturnData getPnameByCode(String code) {

		// 获取编码的类目
		IcdCodeDto gpCode = getGpcode(code);
		String gpName = "";
		if (gpCode != null) {
			gpName = gpCode.getName();
		}

		// 获取编码的亚目
		IcdCodeDto pCode = getPcode(code);
		String pName = "";
		if (pCode != null) {
			pName = pCode.getName();
		}

		Map<String, Object> data = new HashMap<>();
		data.put("gpName", gpName);
		data.put("pName", pName);

		return ReturnUtil.success(data);
	}

	/**
	 * 获取编码的亚目
	 * 
	 * @param code
	 * @return
	 */
	private IcdCodeDto getPcode(String code) {
		// 亚目规则：必定是有小数点且小数点前为三位后面至少有一位的编码才有亚目
		if (code.length() > 4 && code.indexOf(".") == 3) {
			return icdCodeDao.retrieveDtoByCode(code.substring(0, 5));
		}
		return null;
	}

	/**
	 * 获取编码的类目
	 * 
	 * @param code
	 * @return
	 */
	private IcdCodeDto getGpcode(String code) {
		// 类目规则：必定是有小数点且小数点前为三位的编码才有类目
		if ((code.length() > 3 && code.indexOf(".") == 3) || code.length() == 3) {
			return icdCodeDao.retrieveDtoByCode(code.substring(0, 3));
		}
		return null;
	}

	/**
	 * 将code数据提交到数据服务器
	 * 
	 * @param user
	 * 
	 * @return
	 */
	public ReturnData submitServer(User user) throws Exception {
		// 查询是否已存在当晚更新疾病的动作
		long codeUpdateRecordId = icdCodeDao.getCodeUpdateRecordIdBeforeDays(1);
		if (codeUpdateRecordId == 0) {
			// 增加一个动作记录，表示当晚需要更新疾病维表
			icdCodeDao.addUncompletedActionRecord(1, user);
		}

		return ReturnUtil.success();
	}
}
